package com.yy.okhttp;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Map;

/**
 * User: gongyongfeng2@yy.com
 * Date: 2020/8/11 22 :07
 */
public class HttpCodec {
    public static final String CRLF = "\r\n";
    public static final int CR = 13;
    public static final int LF = 10;
    public static final String SPACE = " ";
    public static final String VERSION = "HTTP/1.1";
    public static final String COLON = ":";

    public static final String HEAD_HOST = "Host";
    public static final String HEAD_CONNECTION = "Connection";
    public static final String HEAD_CONTENT_TYPE = "Content-Type";
    public static final String HEAD_CONTENT_LENGTH = "Content-Length";
    public static final String HEAD_TRANSFER_ENCODING = "Transfer-Encoding";

    public static final String HEAD_VALUE_KEEP_ALIVE = "Keep-Alive";
    public static final String HEAD_VALUE_CHUNK = "chunked";

    private ByteBuffer mByteBuffer;

    public void writeRequest(OutputStream os, Request request) throws IOException {
        StringBuffer protocol = new StringBuffer();
        //求情行
        protocol.append(request.getMethod());
        protocol.append(SPACE);
        protocol.append(request.getUrl().file);
        protocol.append(SPACE);
        protocol.append(VERSION);
        protocol.append(CRLF);
        //请求头
        Map<String, String> headers = request.getHeaders();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            protocol.append(entry.getKey());
            protocol.append(COLON);
            protocol.append(SPACE);
            protocol.append(entry.getValue());
            protocol.append(CRLF);
        }
        protocol.append(CRLF);

        RequestBody body = request.getBody();
        if (body != null) {
            body.body();
        }

        os.write(protocol.toString().getBytes());
        os.flush();
    }
}
